<template>
  <div>
    <!--    卡片：将信息集成到卡片容器中-->
    <el-card shadow="always" :body-style="{padding:'20px'}">
      <!--      卡片：表头-->
      <template #header>
        <el-button v-has="'btn.Trademark.add'" @click="addItem" type="primary" icon="ele-Plus">添加</el-button>
      </template>
      <!--      添加或者修改的弹窗-->
      <el-dialog
          v-model="dialogVisible"
          :title=" formData.id?'修改内容':'添加内容'"
          width="30%"
      >
        <el-form
            ref="ruleFormRef"
            label-width="120px"
            class="demo-ruleForm"
            status-icon
            :model="formData"
            :rules="rules"
        >
          <el-form-item label="品牌名称" prop="tmName" style="width: 80%">
            <el-input v-model="formData.tmName"/>
          </el-form-item>
          <el-form-item label="品牌LOGO" prop="logoUrl" style="width: 80%">
            <el-upload
                class="avatar-uploader"
                action="http://gmall-h5-api.atguigu.cn/admin/product/upload"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
            >
              <img v-if="formData.logoUrl" :src="formData.logoUrl" class="avatar"/>
              <el-icon v-else class="avatar-uploader-icon">
                <ele-Plus/>
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="addOrUpdate">
                确认
              </el-button>
            </span>
        </template>
      </el-dialog>
      <!--      表单-->
      <el-table :data="tableData" border stripe style="width: 100%">
        <el-table-column type="index" label="序号" width="80"/>
        <el-table-column prop="tmName" label="品牌名称"/>
        <el-table-column prop="logoUrl" label="品牌Logo">
          <template v-slot="{row}">
            <div>
              <el-image style="width:100px" :src="row.logoUrl" fit="fill" :lazy="true"></el-image>
            </div>
          </template>
        </el-table-column>
        >
        <el-table-column label="操作">
          <template #default="{row}">
            <el-button @click="updateItem(row)" type="warning" size="small" icon="ele-Edit"
                       v-has="'btn.Trademark.update'">修改
            </el-button
            >
            <el-popconfirm title="是不是要删?" @confirm="confirmDelete(row.id)">
              <template #reference>
                <el-button type="danger" size="small" icon="ele-Delete"
                           v-has="'btn.Trademark.remove'">删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!--      分页器-->
      <el-pagination
          :background="true"
          v-model:page-size="count"
          v-model:current-page="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :pager-count="5"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      />
    </el-card>
  </div>
</template>

<script lang="ts">
import {defineComponent} from "vue";

export default defineComponent({
  name: "Trademark",
});
</script>

<script setup lang="ts">
import {onMounted, reactive, ref, watch} from "vue";
import {
  reqDeleteTrademarkItemAsync,
  reqGetTrademarkListAsync,
  reqPostTrademarkItemAsync,
  reqPutTrademarkItemAsync,
  type TrademarkItemType
} from "@/api/trademark";
import {ElMessage, type FormInstance, type FormRules, type UploadProps} from "element-plus";

const tableData = ref<TrademarkItemType[]>([])

// page-size 每页显示的条目个数
const count = ref(10)

// 当前页数
const currentPage = ref(1)

// 总页数
const total = ref(100)

// 页面挂载时 获取 trademark品牌的基本数据
onMounted(() => {
  getTrademarkList()
})

// 获取trademark数据
const getTrademarkList = async () => {
  try {
    const re = await reqGetTrademarkListAsync(currentPage.value, count.value)
    tableData.value = re.records
    total.value = re.total
  } catch (e: any) {
    ElMessage.error(e.message)
  }
}

// 监听页码 和 每一页条数的改变 实时获取数据 页码/条数 响应式的 所以  直接就 渲染对应 的 页码/条数 的数据
watch([currentPage, count], () => {
  // 实时更新数据
  getTrademarkList()
})

// 控制修改/添加弹窗的显示隐藏
const dialogVisible = ref(false)

// 收集表单数据
const formData = ref<TrademarkItemType>({
  tmName: '',  // 品牌名
  logoUrl: ''  // 上传的图片显示隐藏
})

// 收集添加的表单数据
const addItem = () => {

  // 表单校验只要出错就会一直存在
  // 所以每次重新需要校验的时候  清除上一次的校验规则
  ruleFormRef.value?.resetFields()

  // 显示弹窗
  dialogVisible.value = true

  // 清空点完修改formData数据还在的情况
  formData.value = {
    tmName: '',  // 品牌名
    logoUrl: ''  // 上传的图片显示隐藏
  }
}

// 渲染修改的表单数据
const updateItem = (row: TrademarkItemType) => {

  // 表单校验只要出错就会一直存在
  // 所以每次重新需要校验的时候  清除上一次的校验规则
  ruleFormRef.value?.resetFields()

  // 显示弹窗
  dialogVisible.value = true

  // 渲染需要修改的页面
  formData.value = {...row}
}

// 图片上传的功能
const handleAvatarSuccess: UploadProps['onSuccess'] = (  //上传成功的回调
    response,
    uploadFile
) => {
  formData.value.logoUrl = response.data
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {  // 图片校验
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

// 获取form组件的 对象
const ruleFormRef = ref<FormInstance>()

// 点击确定的时候修改或者添加内容
const addOrUpdate = async () => {

  // 表单的整体校验
  // 返回布尔值
  const re = await ruleFormRef.value?.validate(() => {
  })  // () => {}  处理返回promise的报错
  // 为false检验失败 直接return
  if (!re) return

  try {
    //先根据trademarkData中的id判断当前是更新还是新增
    if (formData.value.id) {
      await reqPutTrademarkItemAsync(formData.value);
      ElMessage.success("更新成功");
    } else {
      await reqPostTrademarkItemAsync(formData.value);
      ElMessage.success("新增成功");
    }
  } catch (e: any) {
    ElMessage.error(e.message);
  }
  //关闭弹窗
  dialogVisible.value = false;
  // 重新获取数据
  await getTrademarkList();
}

// 表单校验规则
const rules = reactive<FormRules>({
  tmName: [
    {required: true, message: '请输入品牌名', trigger: 'blur'},
  ],
  logoUrl: [
    {required: true, message: '上传图片', trigger: 'blur'},
  ],
})


// 删除功能
const confirmDelete = async (id: number) => {
  try {
    await reqDeleteTrademarkItemAsync(id)
    ElMessage.success('删除成功');
    // 重新获取数据 刷新页面
    await getTrademarkList()
  } catch (e: any) {
    ElMessage.error(e.message);
  }
}

</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>